package com.team.vlog_temp.Controller;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

@RestController
public class CaptchaController {

    @GetMapping("/captcha") // 访问路径为 /captcha
    public void getCaptcha(HttpSession session, HttpServletResponse response) throws IOException {
        int width = 100;
        int height = 40;
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics g = bufferedImage.getGraphics();

        // 生成随机验证码
        String captcha = generateRandomString(5);
        session.setAttribute("captcha", captcha); // 存储验证码到会话

        // 绘制验证码
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, width, height);
        g.setColor(Color.BLACK);
        g.setFont(new Font("Arial", Font.BOLD, 24));
        g.drawString(captcha, 10, 30);
        g.dispose();

        // 设置响应类型
        response.setContentType("image/png");
        OutputStream out = response.getOutputStream();
        javax.imageio.ImageIO.write(bufferedImage, "png", out);
        out.close();
    }

    private String generateRandomString(int length) {
        String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuilder captcha = new StringBuilder();
        for (int i = 0; i < length; i++) {
            captcha.append(chars.charAt(random.nextInt(chars.length())));
        }
        return captcha.toString();
    }
}
